<template>
  <div class="ele-body">
    <el-card>
    <div class="content_hangs_title">
      <el-radio-group  v-model="where.costTypeId" @input="(v)=>inputchange(v)">
        <el-radio-button label="0000">全部</el-radio-button>
        <el-radio-button v-for="(item) in costTypeDatas" :key="item.id" :label="item.id">{{ item.name }}</el-radio-button>
      </el-radio-group>
      <!-- <div
        class="ele-inline-block hidden-sm-and-down"
        style="width: 260px; margin-left: 10px;margin-top: 10px;margin-right: 10px;margin-bottom: 5px;"
      >
        <el-date-picker
          unlink-panels
          class="ele-fluid"
          
          @change="initTime(null,true)" v-model="currDate" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" :picker-options="setDateRange"
        />
      </div> -->
      <span style="float:right">
        <button type="button"  class="el-button ele-btn-icon el-button--primary el-button--medium button_dc " @click="reportexcel" >
          <i class="el-icon-upload2"></i><span>导 出 </span>
        </button>
      </span>
    </div>
  </el-card>
  <el-card>
    <span style="font-size:18px;font-weight:bold;color:black;">按月统计费用数据</span>
    <div id="myChart" :style="{width: '100%', height: '350px'}"></div>
  </el-card>
  <el-card style="margin-top:15px;margin-bottom:15px">
    <ele-pro-table ref="table" row-key="id" :columns="columns" :datasource="datasource" stripe  :need-page="true" show-summary :summary-method="getSummaries" :cell-style="cellStyle" @row-dblclick="rowdbclick" :height="tableHeight" :full-height="tableFullHeight">
     <!-- 表头工具栏 -->
     <template slot="toolbar">
        <span style="font-size:18px;font-weight:bold;color:black;">费用统计数据</span>
      </template>
      <template slot="M1" slot-scope="{row}">
        {{ row.amounts[0]}}
      </template>
      <template slot="M2" slot-scope="{ row }">
        {{ row.amounts[1] }}
      </template>
      <template slot="M3" slot-scope="{ row}">
        {{ row.amounts[2] }}
      </template>
      <template slot="M4" slot-scope="{ row}">
        {{ row.amounts[3] }}
      </template>
      <template slot="M5" slot-scope="{ row}">
        {{ row.amounts[4] }}
      </template>
      <template slot="M6" slot-scope="{ row }">
        {{ row.amounts[5]}}
      </template>
      <template slot="M7" slot-scope="{ row}">
        {{ row.amounts[6] }}
      </template>
      <template slot="M8" slot-scope="{ row}">
        {{ row.amounts[7] }}
      </template>
      <template slot="M9" slot-scope="{ row}">
        {{ row.amounts[8] }}
      </template>
      <template slot="M10" slot-scope="{ row }">
        {{ row.amounts[9] }}
      </template>
      <template slot="M11" slot-scope="{ row }">
        {{ row.amounts[10] }}
      </template>
      <template slot="M12" slot-scope="{ row }">
        {{ row.amounts[11] }}
      </template>
       <!-- 操作列 -->
       <template slot="action" slot-scope="{ row }"  >
        <el-link type="info"  :underline="false"  icon="el-icon-s-unfold"  @click="openEdit(row)" >明细</el-link>
      </template>
    </ele-pro-table>
  </el-card>
    <!-- 导出数据 -->
    <ExportDialog ref="ExportDialog"></ExportDialog>
     <!-- 编辑弹窗 -->
     <costmanagerDetail :data="current" :visible.sync="showQuery" @done="reload" />
  </div>
</template>

<script>
  import moment from "moment"
  import { removePageTab } from '@/utils/page-tab-util';
  import costmanagerDetail from "./components/costmanager-detail.vue";
  import ExportDialog from '@/components/Excel/ExportDialog'
  import { QueryAllChildDictViewByCode } from '@/api/systemmanager/dictmanager';
  import { QueryCostmanagerSummaryViewByCondition } from '@/api/statistics';

  export default {
    name: 'Cost',
    components: {ExportDialog,costmanagerDetail},
    data() {
      return {
        OneTotal:0,
        TwoTotal:0,
        ThreeTotal:0,
        FourTotal:0,
        FiveTotal:0,
        SixTotal:0,
        SevenTotal:0,
        EngitTotal:0,
        NineTotal:0,
        TenTotal:0,
        EnvelTotal:0,
        TrevalTotal:0,
        columns: [
          { columnKey: 'index', type: 'index', width: 55, align: 'center', showOverflowTooltip: true, fixed: 'left', label:'序号', },
          { prop: 'costTypeDesc', label: '费用类型', showOverflowTooltip: true,align: 'center',},
          { prop: 'M1', label: '1月', slot:'M1',  showOverflowTooltip: true, align: 'center',},
          { prop: 'M2', label: '2月',slot:'M2', showOverflowTooltip: true, align: 'center',},
          { prop: 'M3', label: '3月',slot:'M3', showOverflowTooltip: true, align: 'center',},
          { prop: 'M4', label: '4月', slot:'M4', showOverflowTooltip: true, align: 'center',},
          { prop: 'M5', label: '5月', slot:'M5', showOverflowTooltip: true, align: 'center',},
          { prop: 'M6', label: '6月', slot:'M6', showOverflowTooltip: true, align: 'center',},
          { prop: 'M7', label: '7月', slot:'M7', showOverflowTooltip: true, align: 'center',},
          { prop: 'M8', label: '8月', slot:'M8', showOverflowTooltip: true, align: 'center',},
          { prop: 'M9', label: '9月', slot:'M9', showOverflowTooltip: true, align: 'center',},
          { prop: 'M10', label: '10月', slot:'M10', showOverflowTooltip: true, align: 'center',},
          { prop: 'M11', label: '11月', slot:'M11', showOverflowTooltip: true, align: 'center',},
          { prop: 'M12', label: '12月', slot:'M12', showOverflowTooltip: true, align: 'center',},
          {columnKey: 'action', label: '操作', width: 100, align: 'center', resizable: false,slot: 'action', hideInSetting: true, fixed: 'right', showOverflowTooltip: true}
        ],
        exportList: [
          { keys: "costTypeDesc", name: "费用类型", status: true },
          { keys: 'M1', name: '1月', status: true, },
          { keys: 'M2', name: '2月',status: true,},
          { keys: 'M3', name: '3月',status: true,},
          { keys: 'M4', name: '4月', status: true,},
          { keys: 'M5', name: '5月', status: true,},
          { keys: 'M6', name: '6月', status: true,},
          { keys: 'M7', name: '7月', status: true,},
          { keys: 'M8', name: '8月', status: true,},
          { keys: 'M9', name: '9月', status: true,},
          { keys: 'M10', name: '10月',status: true,},
          { keys: 'M11', name: '11月', status: true,},
          { keys: 'M12', name: '12月', status: true,},
        ],
        fixedHeight:true,
        current:null,
        showQuery:false,
        currDate:'',
        activeDate:'1',
        costTypeDatas:[],
        where: {costTypeId:this.Constant.DefaultCostsId,costTypeDesc:''},
      };
    },
    created(){
      this.init();
    },
    mounted() {
      
      // this.drawBar();
      // this.reload();
    },
    computed: {
      // 表格高度
      tableHeight() {
        var fh = this.fixedHeight ? 'calc(100vh - 450px)' : void 0;
        return fh;
      },
      // 表格全屏时高度
      tableFullHeight() {
        var fh =  this.fixedHeight ? 'calc(100vh - 350px)' : null;
        return fh;
      },
    },
    methods: {

      init(){
        QueryAllChildDictViewByCode(this.Constant.C_GLFY).then((d)=>{
          this.costTypeDatas = [];
          this.costTypeDatas = d;
        });
      },

      inputchange(v){
        this.reload();
      },

      /* 表格数据源 */
      async datasource(params) {

       

        params.where.pageindex = params.page;
        params.where.pagesize = params.limit;

        //添加排序
        if(params.order.order == null || params.order.order == undefined){
          params.where.orderBys = [{ sort: "createDate", order: 1, }];
        }else{
          params.where.orderBys = [];
          params.where.orderBys.push({sort:params.sorter.column.sortable,order:params.order.order=='asc'?0:1});
        }

        if(!params.where.conditions)params.where.conditions = {};

        if(params.where.costTypeId == this.Constant.DefaultCostsId) params.where.costTypeId = null;

        let data = await QueryCostmanagerSummaryViewByCondition(params.where);

        this.$nextTick(() => {
          this.$refs.table.doLayout();
        });

        this.drawBar(data);

        return {
            list:data.itemList,
            count:data.totalCount,
        };
      },

      openEdit(row){
        removePageTab({ key: '/statistics/costmanager/detail' });
        this.$nextTick(() => {
          this.$router.push({path: '/statistics/costmanager/detail', query: { "costTypeId":row.costTypeId } });
        });
      },
      //刷新表格
      reload(where) {
        this.$refs.table.reload({ where: this.where });
      },
      
      /* 导出 */
      reportexcel(pams) {
        
        var dataArray =[];
        this.$refs.table.tableData.map((t)=>{
          
          var array = {'costTypeDesc':t.costTypeDesc};
          t.amounts.map((a,index)=>{

            if(index == 0)  {array.M1 = a}
            if(index == 1)  {array.M2 = a}
            if(index == 2)  {array.M3 = a}
            if(index == 3)  {array.M4 = a}
            if(index == 4)  {array.M5 = a}
            if(index == 5)  {array.M6 = a}
            if(index == 6)  {array.M7 = a}
            if(index == 7)  {array.M8 = a}
            if(index == 8)  {array.M9 = a}
            if(index == 9)  {array.M10 = a}
            if(index == 10)  {array.M11 = a}
            if(index == 11)  {array.M12 = a}
          })

          dataArray.push(array);
        });

        this.$refs.ExportDialog.showEdits = true
        this.$refs.ExportDialog.checkList = this.exportList
        this.$refs.ExportDialog.titleName = "费用统计列表"
        this.$refs.ExportDialog.dataList = dataArray;
      },

      drawBar(data) {
        // 基于准备好的dom，初始化echarts实例
        var xDatas =[];
        var yDatas = [];
        let myChart = this.$echarts.getInstanceByDom(document.getElementById("myChart") );
        //然后判断实例是否存在，如果不存在，就创建新实例
        if (myChart == null) {
            myChart = this.$echarts.init(document.getElementById("myChart"));
        }
        if(data?.chartDataList ){
          data.chartDataList.map((item)=>{

            if(!xDatas.includes(item.month+'月')){
                xDatas.push(item.month+'月');
              }

            if(this.where.costTypeId!=this.Constant.DefaultCostsId){
              if(item.costTypeId == this.where.costTypeId){
                yDatas.push(item.amount);
              }else{
                yDatas.push(0);
              }
            }else{
              yDatas.push(item.amount);
            }
          });
        }
        // 绘制图表
        myChart.setOption({
          tooltip: {
              trigger: 'axis',
              renderMode: 'richText',
              confine: true,
              extraCssText: 'z-index: 9999',
              textStyle: {
                textShadowColor: 'transparent',//文字块背景阴影颜色
                textShadowBlur: 10,//文字块的背景阴影长度
              }
          },
          grid: {
              top: '25%',
              left: '2%',
              right: '2%',
              bottom: '5%',
              containLabel: true
          },
          legend: {
              // data: ['在线', '离线', '在线率'],
              x: 'center',
              top: '10%',
              orient: 'horizontal',
              itemWidth: 16,
              itemHeight: 12
          },
          xAxis: [
              {
                type: 'category',
                axisLine: {
                    onZero: false,
                    lineStyle: {
                      color: "#e5e5e5"
                    }
                },
                axisLabel: { //坐标轴字体颜色
                    textStyle: {
                      color: '#999999'
                    }
                },
                axisTick: { //y轴刻度线
                    show: false
                },
                splitLine: { //网格
                    show: false,
                },
                data: xDatas,
              }
          ],
          yAxis: [
              {
                name: '费用类型',
                type: 'value',
                axisLabel: { //坐标轴字体颜色
                    textStyle: {
                      color: '#9eaaba'
                    }
                },
                splitLine: { //网格
                    show: true,
                    lineStyle: {
                      color: '#dadde4',
                      type: "dashed"
                    }
                }
              },
              {
                name: '趋势',
                min: 1,
                type: 'value',
                axisLabel: { //坐标轴字体颜色
                  textStyle: {
                    color: '#9eaaba'
                  }
                },
                axisTick: { //y轴刻度线
                  show: false
                },
                splitLine: { //网格
                  show: false
                }
              }
          ],
          series: [
          {
            name: '费用类型',
            type: 'bar',
            barWidth: 14, //柱子宽度
            itemStyle: { //柱子颜色
                normal: {
                  color: '#00BA56',
                  borderRadius: 10
                }
            },
            data: yDatas,
          },
          {
            name: '趋势',
            type: 'line',
            symbolSize: 6,
            yAxisIndex: 1,
            lineStyle: {
                color: '#2163E0',
                width: 3
            },
            itemStyle: {
                borderColor: '#2163E0',
                borderWidth: 5
            },
            data:  yDatas,
          }]
        });
      },

      rowdbclick(row,col,e){
        this.current = row;
        this.showQuery = true;
      },

      /* 合计 */
      getSummaries(param){
        const sums = [];
        sums[0] = '合计' ;
        const { columns, data } = param;

        columns.forEach((column, index) => {
          if(index ==2){
            const v1 = data.map((m)=>{ return parseFloat(m.amounts[0]) });
            
            sums[index] =v1 && v1.length>0 ?v1.reduce((pre,curr)=>{
              const value = parseFloat(curr);
              return  !isNaN(value)?(parseFloat(pre) + value): parseFloat(pre);
            }):0;
          }else if(index ==3){
            const v2 = data.map((m)=>{ return parseFloat(m.amounts[1]) });
            sums[index] =v2  && v2.length>0 ? v2.reduce((pre,curr)=>{
              const value = parseFloat(curr);
              return  !isNaN(value)?(parseFloat(pre) + value): parseFloat(pre);
            }):0
          }else if(index ==4){
            const v3 = data.map((m)=>{ return parseFloat(m.amounts[2]) });
            sums[index] =v3  && v3.length>0 ? v3.reduce((pre,curr)=>{
              const value = parseFloat(curr);
              return  !isNaN(value)?(parseFloat(pre) + value): parseFloat(pre);
            }):0
          }else if(index ==5){
            const v4 = data.map((m)=>{ return parseFloat(m.amounts[3]) });
            sums[index] =v4  && v4.length>0 ? v4.reduce((pre,curr)=>{
              const value = parseFloat(curr);
              return  !isNaN(value)?(parseFloat(pre) + value): parseFloat(pre);
            }):0;
          }else if(index ==6){
            const v5 = data.map((m)=>{ return parseFloat(m.amounts[4]) });
            sums[index] =v5  && v5.length>0 ? v5.reduce((pre,curr)=>{
              const value = parseFloat(curr);
              return  !isNaN(value)?(parseFloat(pre) + value): parseFloat(pre);
            }):0;
          }else if(index ==7){
            const v6 = data.map((m)=>{ return parseFloat(m.amounts[5]) });
            sums[index] =v6  && v6.length>0 ? v6.reduce((pre,curr)=>{
              const value = parseFloat(curr);
              return  !isNaN(value)?(parseFloat(pre) + value): parseFloat(pre);
            }):0;
          }else if(index ==8){
            const v7 = data.map((m)=>{ return parseFloat(m.amounts[6]) });
            sums[index] = v7  && v7.length>0 ? v7.reduce((pre,curr)=>{
              const value = parseFloat(curr);
              return  !isNaN(value)?(parseFloat(pre) + value): parseFloat(pre);
            }):0
          }else if(index ==9){
            const v8 = data.map((m)=>{ return parseFloat(m.amounts[7]) });
            sums[index] =v8  && v8.length>0 ? v8.reduce((pre,curr)=>{
              const value = parseFloat(curr);
              return  !isNaN(value)?(parseFloat(pre) + value): parseFloat(pre);
            }):0
          }else if(index ==10){
            const v9 = data.map((m)=>{ return parseFloat(m.amounts[8]) });
            sums[index] =v9  && v9.length>0 ? v9.reduce((pre,curr)=>{
              const value = parseFloat(curr);
              return  !isNaN(value)?(parseFloat(pre) + value): parseFloat(pre);
            }):0
          }else if(index ==11){
            const v10 = data.map((m)=>{ return parseFloat(m.amounts[9]) });
            sums[index] = v10  && v10.length>0 ? v10.reduce((pre,curr)=>{
              const value = parseFloat(curr);
              return  !isNaN(value)?(parseFloat(pre) + value): parseFloat(pre);
            }):0
          }else if(index ==12){
            const v11 = data.map((m)=>{ return parseFloat(m.amounts[10]) });
            sums[index] = v11  && v11.length>0 ? v11.reduce((pre,curr)=>{
              const value = parseFloat(curr);
              return  !isNaN(value)?(parseFloat(pre) + value): parseFloat(pre);
            }):0
          }else if(index ==13){
            const v12 = data.map((m)=>{ return parseFloat(m.amounts[11]) });
            sums[index] =v12  && v12.length>0 ? v12.reduce((pre,curr)=>{
              const value = parseFloat(curr);
              return  !isNaN(value)?(parseFloat(pre) + value): parseFloat(pre);
            }):0
          }
        });

        this.$nextTick(() => {
          this.$refs.table.doLayout();
        });
        
        return sums;
      },

      /* 样式 */
      cellStyle(param){
        const { row, column, rowIndex, columnIndex } = param;
        if(columnIndex ==2||columnIndex ==3||columnIndex ==4||columnIndex ==5||columnIndex ==6||columnIndex ==7||columnIndex ==8||columnIndex ==9||columnIndex ==10||columnIndex ==11||columnIndex ==12||columnIndex ==13){
          return{
            color:''
          }
        }
      },
    }
  };
</script>
 <style lang="scss" scoped>

/*总计字体颜色
::v-deep .el-table__footer-wrapper tbody td {
    color: var(--color-primary);
    cursor: pointer;
  }*/

 
</style>